//TokenCenter.js
// 智能合约地址
import Web3 from "web3";
import {MSGSENDER} from "./TokenCenter"
import {ExchangeABI} from "./contractABI"
import "nprogress/nprogress.css"
import TimeStatus from "./Time"
import {Message, Notification} from 'element-ui';
import {configure, done, start} from "nprogress"
// 智能合约ABI
const web3 = new Web3(Web3.givenProvider);
let contract;
configure({
    trickleSpeed: 20,
})

/**
 * 初始化
 * @param option
 */
async function  Init(option){
    contract = new web3.eth.Contract(ExchangeABI, option);
    return true
}

/**
 * Token注入交易池
 * @param option Exchange Address
 * @param extra  Token Price
 * @param callback  返回值
 */
function tokenIntoPool(option,extra,callback){
    Init(option).then(r=>{
        if(r){
            console.log(extra)
            contract.methods.initializeExchange(extra.amount).send({from:MSGSENDER,value:extra.price*extra.amount})
                .on('receipt', function(receipt){
                    callback(true)
                    // receipt 相关例子
                })
                .on('error', function(error, receipt) {
                    // 如果交易被网络拒绝并带有交易收据，则第二个参数将是交易收据。
                })
        }
    })
}

/**
 *通过Exchange Address 获取对应 Token 的 Price
 * @param option     Exchange Address
 * @param callback   Token  Price
 */
function getTokenPriceByExchangeAddress(option,callback) {
    Init(option).then(r => {
        if(r){
            contract.methods.tokenFee().call()
                .then(res=>{
                    callback(res/1000)
                })
        }
    })
}

/**
 * 通过Eth 购买 Token
 * @param option token交易池地址
 * @param extra 携带参数
 * @param callback 返回值
 */
function ethTokenSwap(option,extra,callback) {
    Init(option).then(r => {
        if(r){
                // console.log("MSG",)
            console.log(extra.tokenPay)
            contract.methods.ethToTokenSwap(extra.tokenValue,TimeStatus.dataToUnix(extra.tokenLimitTime)).estimateGas({from:MSGSENDER,value:extra.tokenPay})
                .then(function(gasAmount){
                    console.log(gasAmount)
                    contract.methods.ethToTokenSwap(extra.tokenValue,TimeStatus.dataToUnix(extra.tokenLimitTime)).send({from:MSGSENDER,value:extra.tokenPay})
                        .on('transactionHash', function(hash){
                            Message.success("您已提交一笔交易")
                            start()
                        })
                        .on('confirmation', function(confirmationNumber, receipt){

                        })
                        .on('receipt', function(receipt){
                            done()
                            Message.success("您已交易成功")
                            Notification({
                                title:"交易收据",
                                type:"success",
                                dangerouslyUseHTMLString: true,
                                message: `<strong>交易哈希 <i style="color: cadetblue">${receipt.blockHash}</i></strong><br><strong>交易账号 <i style="color: cadetblue">${receipt.from}</i></strong><br>`
                            })
                            console.log(receipt)
                            callback(true)
                            // receipt 相关例子

                        })
                        .on('error', function(error, receipt) {
                            // 如果交易被网络拒绝并带有交易收据，则第二个参数将是交易收据。
                        })
                })
                .catch(function(error){
                });
        }
    })
}

/**
 * 出售token以获取Eth
 * @param option token交易池地址
 * @param extra 携带参数
 * @param callback 返回值
 */
function tokenEthSwap(option,extra,callback) {
    Init(option).then(r => {
        if(r){
            // console.log("MSG",)
            console.log(extra.tokenPay)
            contract.methods.tokenToEthSwap(extra.tokenValue,extra.tokenPay,TimeStatus.dataToUnix(extra.tokenLimitTime)).estimateGas({from:MSGSENDER})
                .then(function(gasAmount){
                    console.log(gasAmount)
                    contract.methods.tokenToEthSwap(extra.tokenValue,extra.tokenPay,TimeStatus.dataToUnix(extra.tokenLimitTime)).send({from:MSGSENDER})
                        .on('transactionHash', function(hash){
                            Message.success("您已提交一笔交易")
                            start()
                        })
                        .on('confirmation', function(confirmationNumber, receipt){

                        })
                        .on('receipt', function(receipt){
                            done()
                            Message.success("您已交易成功")
                            Notification({
                                title:"交易收据",
                                type:"success",
                                dangerouslyUseHTMLString: true,
                                message: `<strong>交易哈希 <i style="color: cadetblue">${receipt.blockHash}</i></strong><br><strong>交易账号 <i style="color: cadetblue">${receipt.from}</i></strong><br>`
                            })
                            console.log(receipt)
                            callback(true)
                            // receipt 相关例子

                        })
                        .on('error', function(error, receipt) {
                            // 如果交易被网络拒绝并带有交易收据，则第二个参数将是交易收据。
                            Notification({
                                title:"交易收据",
                                type:"error",
                                dangerouslyUseHTMLString: true,
                                message: `<strong>交易哈希 <i style="color: cadetblue">${receipt.blockHash}</i></strong><br>`
                            })
                        })
                })
                .catch(function(error){
                });
        }
    })
}

/**
 * 获取Token交易记录
 * @param option
 * @param extra
 * @param callback
 */
function transferInfo(option,extra,callback) {
    Init(option).then(r=>{
        if(r){
            contract.methods.getTokenInfo().call()
                .then(r=>{
                    console.log(r)
                })
        }
    })
}

function tokenPriceList(option,callback) {
    Init(option).then(r=>{
        if(r){
            contract.methods.getTokenPrice().call()
                .then(r=>{
                    console.log(r)
                })
        }
    })
}

function getTokenInfoList(option,callback){
    Init(option).then(r=>{
        if(r){
            contract.methods.getTokenInfo().call()
                .then(r=>{
                    callback(r)
                })
        }
    })
}



//导出相应的方法
export default {
    Init,
    tokenIntoPool,
    getTokenPriceByExchangeAddress,
    ethTokenSwap,
    tokenEthSwap,
    tokenPriceList,
    getTokenInfoList
}
